import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import { useDevToolsStore, createApiInterceptor } from '@/stores/devToolsStore'
import { API_CONFIG } from './apiConfig'
import { mockApi } from './mockApi'
import { ExtendedApiClient } from './api'

// 开发模式增强的API客户端
class DevApiClient {
    private axiosInstance: AxiosInstance
    private devToolsStore: any

    constructor() {
        this.axiosInstance = axios.create({
            baseURL: API_CONFIG.BASE_URL,
            timeout: API_CONFIG.TIMEOUT,
            headers: {
                'Content-Type': 'application/json',
            },
        })

        this.setupInterceptors()
    }

    private setupInterceptors() {
        // 只在开发环境设置拦截器
        if (process.env.NODE_ENV === 'development') {
            const interceptor = createApiInterceptor()

            // 请求拦截器
            this.axiosInstance.interceptors.request.use(
                (config) => {
                    // 记录请求开始时间
                    (config as any).metadata = { startTime: Date.now() }

                    // 如果启用了开发工具，记录API调用
                    const devStore = useDevToolsStore.getState()
                    if (devStore.isEnabled) {
                        console.group(`🚀 API Request: ${config.method?.toUpperCase()} ${config.url}`)
                        console.log('Config:', config)
                        console.log('Headers:', config.headers)
                        if (config.data) {
                            console.log('Data:', config.data)
                        }
                        console.groupEnd()
                    }

                    return interceptor.request(config)
                },
                (error) => {
                    console.error('❌ Request Error:', error)
                    return Promise.reject(error)
                }
            )

            // 响应拦截器
            this.axiosInstance.interceptors.response.use(
                (response) => {
                    const duration = Date.now() - ((response.config as any).metadata?.startTime || 0)

                    const devStore = useDevToolsStore.getState()
                    if (devStore.isEnabled) {
                        console.group(`✅ API Response: ${response.config.method?.toUpperCase()} ${response.config.url}`)
                        console.log('Status:', response.status)
                        console.log('Duration:', `${duration}ms`)
                        console.log('Data:', response.data)
                        console.log('Headers:', response.headers)
                        console.groupEnd()
                    }

                    return interceptor.response(response)
                },
                (error) => {
                    const duration = Date.now() - ((error.config as any)?.metadata?.startTime || 0)

                    const devStore = useDevToolsStore.getState()
                    if (devStore.isEnabled) {
                        console.group(`❌ API Error: ${error.config?.method?.toUpperCase()} ${error.config?.url}`)
                        console.log('Status:', error.response?.status)
                        console.log('Duration:', `${duration}ms`)
                        console.log('Error:', error.message)
                        if (error.response?.data) {
                            console.log('Response Data:', error.response.data)
                        }
                        console.groupEnd()
                    }

                    return interceptor.error(error)
                }
            )
        }
    }

    // 通用请求方法
    async request<T = any>(config: AxiosRequestConfig): Promise<T> {
        const devStore = useDevToolsStore.getState()

        // 如果启用了模拟API，使用模拟数据
        if (devStore.useMockApi) {
            return this.handleMockRequest<T>(config)
        }

        try {
            const response: AxiosResponse<T> = await this.axiosInstance.request(config)
            return response.data
        } catch (error) {
            throw error
        }
    }

    // 处理模拟请求
    private async handleMockRequest<T = any>(config: AxiosRequestConfig): Promise<T> {
        const devStore = useDevToolsStore.getState()
        const { method = 'GET', url = '', data } = config

        console.log(`🎭 Mock API: ${method.toUpperCase()} ${url}`)

        // 根据模拟数据模式调整响应
        const mockDataMode = devStore.mockDataMode

        // 模拟延迟
        const delay = this.getMockDelay(mockDataMode)
        await new Promise(resolve => setTimeout(resolve, delay))

        // 模拟错误场景
        if (mockDataMode === 'error') {
            throw new Error('Mock API Error: Simulated error scenario')
        }

        // 路由到对应的模拟API方法
        try {
            const result = await this.routeMockRequest(method, url, data, mockDataMode)
            return result as T
        } catch (error) {
            console.error('Mock API Error:', error)
            throw error
        }
    }

    // 获取模拟延迟时间
    private getMockDelay(mode: string): number {
        switch (mode) {
            case 'slow':
                return 2000 + Math.random() * 3000 // 2-5秒
            case 'fast':
                return 50 + Math.random() * 100 // 50-150ms
            default:
                return 200 + Math.random() * 300 // 200-500ms
        }
    }

    // 路由模拟请求到对应的方法
    private async routeMockRequest(method: string, url: string, data: any, mode: string): Promise<any> {
        const urlParts = url.split('/').filter(Boolean)

        // 根据URL路径路由到对应的模拟API方法
        if (urlParts.includes('datasets')) {
            if (method === 'GET' && urlParts.length === 2) {
                return await mockApi.getDatasets()
            } else if (method === 'GET' && urlParts.length === 3) {
                return await mockApi.getDataset(urlParts[2])
            } else if (method === 'POST') {
                return await mockApi.createDataset(data)
            }
        } else if (urlParts.includes('images')) {
            const imageId = urlParts[urlParts.indexOf('images') + 1]
            if (method === 'GET') {
                return await mockApi.getImageData(imageId)
            }
        } else if (urlParts.includes('tasks')) {
            if (method === 'GET' && urlParts.includes('datasets')) {
                const datasetId = urlParts[urlParts.indexOf('datasets') + 1]
                return await mockApi.getTasks(datasetId)
            } else if (method === 'POST' && urlParts.includes('start')) {
                return await mockApi.startTask(data.taskId, data.params)
            }
        }

        // 默认返回空响应
        return { message: 'Mock response', data: null }
    }

    // HTTP方法快捷方式
    async get<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
        return this.request<T>({ ...config, method: 'GET', url })
    }

    async post<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
        return this.request<T>({ ...config, method: 'POST', url, data })
    }

    async put<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
        return this.request<T>({ ...config, method: 'PUT', url, data })
    }

    async delete<T = any>(url: string, config?: AxiosRequestConfig): Promise<T> {
        return this.request<T>({ ...config, method: 'DELETE', url })
    }

    async patch<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
        return this.request<T>({ ...config, method: 'PATCH', url, data })
    }
}

// 创建开发API客户端实例
export const devApiClient = new DevApiClient()

// 开发工具增强的API客户端包装器
export const createDevApiClient = (): ExtendedApiClient => {
    return {
        // 数据集相关
        async getDatasets() {
            return devApiClient.get('/datasets')
        },

        async getDataset(id: string) {
            return devApiClient.get(`/datasets/${id}`)
        },

        async createDataset(data) {
            return devApiClient.post('/datasets', data)
        },

        async updateDataset(id: string, data) {
            return devApiClient.put(`/datasets/${id}`, data)
        },

        async deleteDataset(id: string) {
            return devApiClient.delete(`/datasets/${id}`)
        },

        async getDatasetStats(id: string) {
            return devApiClient.get(`/datasets/${id}/stats`)
        },

        async getDatasetsWithPagination(pagination) {
            return devApiClient.get('/datasets', { params: pagination })
        },

        // 影像数据相关
        async getImageData(imageId: string) {
            return devApiClient.get(`/images/${imageId}/data`)
        },

        async getImageMetadata(imageId: string) {
            return devApiClient.get(`/images/${imageId}/metadata`)
        },

        async uploadImages(datasetId: string, files: File[]) {
            const formData = new FormData()
            files.forEach(file => formData.append('files', file))
            return devApiClient.post(`/datasets/${datasetId}/images`, formData, {
                headers: { 'Content-Type': 'multipart/form-data' }
            })
        },

        async deleteImages(imageIds: string[]) {
            return devApiClient.delete('/images', { data: { imageIds } })
        },

        // 任务相关
        async getTasks(datasetId: string) {
            return devApiClient.get(`/datasets/${datasetId}/tasks`)
        },

        async createTask(data) {
            return devApiClient.post('/tasks', data)
        },

        async updateTask(id: string, data) {
            return devApiClient.put(`/tasks/${id}`, data)
        },

        async deleteTask(id: string) {
            return devApiClient.delete(`/tasks/${id}`)
        },

        async startTask(taskId: string, params) {
            return devApiClient.post('/tasks/start', { taskId, params })
        },

        async cancelTask(id: string) {
            return devApiClient.post(`/tasks/${id}/cancel`)
        },

        async getTaskStatus(taskId: string) {
            return devApiClient.get(`/tasks/${taskId}/status`)
        },

        async getTaskResults(taskId: string) {
            return devApiClient.get(`/tasks/${taskId}/results`)
        },

        async getTasksWithPagination(datasetId: string, pagination) {
            return devApiClient.get(`/datasets/${datasetId}/tasks`, { params: pagination })
        },

        // 健康检查
        async healthCheck() {
            return devApiClient.get('/health')
        }
    }
}

export default devApiClient